﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MetadataBasedConfigArch.Framework.Model;

namespace MetadataBasedConfigArch.Framework.Processor
{
    public static class ConfigurableProcessorFactory
    {
        public static IConfigurableProcessor<T> Create<T>(T configurable, IMetadataBasedEntityProvider entityProvider)
            where T : IConfigurable
        {
            return Create(configurable, entityProvider) as IConfigurableProcessor<T>;
        }

        public static IConfigurableProcessor Create(IConfigurable configurable, IMetadataBasedEntityProvider entityProvider)
        {
            String configTypeName = Helper.GetConfigurableConfigTypeName(configurable.GetType());

            IConfigMeta configMeta = configurable.ConfigMetaInst;
            if (configMeta == null)
            {
                configMeta = entityProvider.GetConfigMeta(configTypeName, configurable.ConfigMetaContent);
            }

            if (configMeta != null && configMeta.ConfigTypeInst != null)
            {
                Type processorType = Type.GetType(configMeta.ConfigTypeInst.ProcessorClass);
                if (processorType!=null && typeof(IConfigurableProcessor).IsAssignableFrom(processorType) && processorType.IsClass)
                {
                    IConfigurableProcessor processor = Activator.CreateInstance(processorType) as IConfigurableProcessor;
                    if (processor != null)
                    {
                        processor.TargetConfigurable = configurable;
                        processor.EntityProvider = entityProvider;
                        return processor;
                    }
                }
            }
            return null;
        }
    }
}
